package com.example.demo.service;

import com.baomidou.mybatisplus.extension.api.R;
import com.example.demo.Bean.Result;
import com.example.demo.Bean.UserTable;
import com.example.demo.Utils.SqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class SqlService {

    @Autowired
    private SqlUtil sqlUtil;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    public Result connect(String studentUid) throws Exception{
        Result result = null;
        sqlUtil.connect(studentUid);
        result = new Result(200,"当前操作数据库为： _"+studentUid);
        return result;
    }

    public Result sql(String sql,String studentUid) throws Exception{
        if(!(sql.trim().equals("")) && sql.contains("information_schema")){
            return new Result(402, "无权访问information_schema!");
        }
        sql = sql.replace("\n","");
        String[] sqls = sql.split(";");
        Result result = null;
        ResultSet resultSet = null;
        String error = null;
        StringBuilder message = new StringBuilder();
            for(int i = 0 ; i < sqls.length ; i++) {
                try {
                    resultSet = sqlUtil.sql(sqls[i], studentUid);
                    if (resultSet != null) {
                        UserTable resultMap = sqlUtil.packResultSet(resultSet);
                        result = new Result(200, resultMap);
                        resultSet.close();
                    }
                    message.append(dateFormat.format(new Date()) + "---" + sqls[i] + "---execute OK </br></br>");
                }catch (java.sql.SQLException e){
                    error = e.toString();
                    message.append(dateFormat.format(new Date()) + "---" + sqls[i] + "---" + error.substring(error.indexOf(":") + 1) +"</br></br>");
                }catch (Exception exception){
                    return new Result(500,exception.toString());
                }
            }
            if(result == null){
                result = new Result(200,message.toString());
            }
            result.setMessage(message.toString());
        return result;
    }

    public Result closeConnection(String studentUid) throws Exception{
        Result result = null;
        sqlUtil.closeConnection(studentUid);
        result = new Result(200,"已关闭连接");
        return result;
    }

}
